package com.wu.service.impl;

import com.wu.mapper.ArticlesMapper;
import com.wu.pojo.Articles;
import com.wu.pojo.model.UserToken;
import com.wu.service.CollectArticleService;
import com.wu.util.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.wu.constant.Constant.*;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-05-07 13:58
 */
@Service
public class CollectArticleServiceImpl implements CollectArticleService {

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ArticlesMapper articlesMapper;

    @Override
    public Map<String, Object> getCollectArticleByUserId(String userId, Integer curPage) {
        Map<String, Object> map = new HashMap<>();
        Set<Object> collectIds = redisTemplate.opsForSet().members(userId + _COLLECT);
        map.put(COUNT, collectIds.size());
        int totalPage = (collectIds.size() + DEFAULT_PAGE_SIZE - 1) / DEFAULT_PAGE_SIZE;
        if (totalPage == 0) {
            map.put(TOTAL_PAGE, 0);
            map.put(COLLECT, new ArrayList<>());
            return map;
        }
        if (curPage < 1) {
            curPage = 1;
        }
        if (curPage > totalPage) {
            curPage = totalPage;
        }
        map.put(TOTAL_PAGE, totalPage);
        ArrayList<String> ids = new ArrayList<>();
        Object[] objectIds = collectIds.toArray();
        for (int i = 0; i < (Math.min(objectIds.length, 10)); i++) {
            ids.add((String) objectIds[((curPage - 1) * 10 + i)]);
        }
        List<Articles> collectArticles = articlesMapper.getArticleCollectByIds(ids);
        map.put(COLLECT, collectArticles);
        return map;
    }

    @Override
    public boolean addOrDeleteCollect(String articleId) {
        UserToken userToken = tokenUtils.parseTokenToUserToken();
        String userId = userToken.getUserId();
        //看看用户是否已经添加了收藏
        Boolean isCollect = redisTemplate.opsForSet().isMember(userId + _COLLECT, articleId);
        if (Boolean.TRUE.equals(isCollect)) {
            //说明用户已经收藏过了，现在是取消收藏
            redisTemplate.opsForSet().remove(userId + _COLLECT, articleId);
            redisTemplate.opsForValue().decrement(articleId + _COLLECT_COUNT);
            redisTemplate.opsForSet().remove(articleId + _COLLECT_USER, userId);
            redisTemplate.opsForValue().decrement(userId + _COLLECT_COUNT);
            return false;
        } else {
            redisTemplate.opsForSet().add(userId + _COLLECT, articleId);
            redisTemplate.opsForValue().increment(articleId + _COLLECT_COUNT);
            redisTemplate.opsForSet().add(articleId + _COLLECT_USER, userId);
            redisTemplate.opsForValue().increment(userId + _COLLECT_COUNT);
            return true;
        }
    }
}
